/**
 * 
 */
package ac.svn.accesscontrol.ui;

import java.util.Set;

import javax.swing.DefaultListModel;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.SwingUtilities;

import ac.svn.accesscontrol.store.IResources;
import ac.svn.accesscontrol.store.ISVNItem;
import ac.svn.accesscontrol.utils.Utility;

/**
 * @author Enigmanic
 *
 */
public class ContentLister {
	private boolean listClrRequired = false;
	private DefaultListModel listModel;
	private JLabel statusLabel;
	private Thread listingThread;
	private JList targetList;
	private Set<ISVNItem> sourceFiles;
	
	public ContentLister(String componentId,String modelId)
	{
		targetList = (JList) UIComponentLibrary.getComponent(componentId);
		listModel =  (DefaultListModel) UIComponentLibrary.getComponent(modelId);
		statusLabel = (JLabel) UIComponentLibrary.getComponent(IUIConstants.C_STATUS_LABEL);		
		
		listingThread = new Thread(new Runnable() {
			@Override
			public void run() {
				
				if(null == sourceFiles || sourceFiles.isEmpty())
				{
					return;
				}
				
				if(isListClrRequired())
				{
					listModel.removeAllElements();
				}
				
				for(ISVNItem  svnItem  : sourceFiles )
				{
					listModel.addElement(svnItem);
				}
				
				SwingUtilities.invokeLater(new Runnable() {
					@Override
					public void run() {
						SwingUtilities.updateComponentTreeUI(targetList);
						if(isListClrRequired())
						{
							statusLabel.setText("Listing complete!");
							statusLabel.setIcon(Utility.getImageIcon(IResources.LOC_ICN_DONE));
						}					
					}
				});

			}
		});
	}
	
	public void listItem(Set<ISVNItem> svnItems)
	{
		sourceFiles = null;
		sourceFiles =  svnItems;
		refresh();
	}
	
	public void setListClrRequired(boolean listClrRequired) {
		this.listClrRequired = listClrRequired;
	}

	public boolean isListClrRequired() {
		return listClrRequired;
	}
	
	public void refresh()
	{
		if(listingThread.isAlive())
		{
			listingThread.interrupt();
		}
		listingThread.run();
	}
	
	public void addItem(ISVNItem svnItem)
	{
		sourceFiles.add(svnItem);
		refresh();
	}
	
}
